/*
 * Copyright 2014 Jonathan Haas
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package app.grinreader.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import app.grinreader.R;
import app.grinreader.library.BookData;
import app.grinreader.library.Library;
import app.grinreader.model.BookModel;
import app.grinreader.model.BookPosition;
import app.grinreader.render.BookView;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.epub.EpubReader;

import java.io.IOException;


public class ReadActivity extends Activity {
    public static final String EXTRA_BOOK_FILE = "BOOK_FILE";
    private BookModel bookModel;
    private Library library;
    private BookData bookData;
	private BookView bookView;
	private String bookFile;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        library = new Library(this);
		initUi();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		bookData.setReadingPosition(bookView.getStartPosition());
		initUi();
		loadBookModel(bookModel);
	}

	private void initUi() {
		setContentView(R.layout.reader);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		bookView = ((BookView) findViewById(R.id.view));
	}

	@Override
    protected void onStart() {
        super.onStart();
        Bundle extras = getIntent().getExtras();
        try {
            if (extras != null) {
	            bookFile = extras.getString(EXTRA_BOOK_FILE);
                if (bookFile != null) {
                    loadBook(bookFile);
                    return;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        // unload Book
	    try {
		    bookData.setReadingPosition(bookView.getStartPosition());
		    library.saveBookData(bookFile, bookData);
	    } catch (IOException e) {
		    e.printStackTrace();
	    }
    }

    private void loadBook(String bookFile) throws IOException {
        bookData = library.getBookData(bookFile);
        new AsyncTask<String, Integer, BookModel>(){
            @Override
            protected BookModel doInBackground(String... params) {
                Book book = null;
                try {
                    book = new EpubReader().readEpubLazy(params[0], "UTF-8");
                } catch (IOException e) {
                    Log.e("reader", "error", e);
                    return null;
                }
                bookModel = new BookModel(book);
                return bookModel;
            }

            @Override
            protected void onPostExecute(BookModel bookModel) {
	            loadBookModel(bookModel);
            }
        }.execute(bookFile);
    }

	private void loadBookModel(BookModel bookModel) {
		if(bookModel == null) return;
		bookView.setBookModel(bookModel);
		BookPosition readingPosition = bookData.getReadingPosition();
		if(readingPosition != null){
		    bookView.setStartPosition(readingPosition);
		}
		else {
			bookView.setStartPosition(bookModel.getStartPosition());
		}
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        new MenuInflater(this).inflate(R.menu.reader, menu);
        return super.onCreateOptionsMenu(menu);
    }

    public void onNext(MenuItem item) {
	    bookView.setStartPosition(bookView.getEndPosition());
    }
	public void onPrev(MenuItem item) {
        bookView.setEndPosition(bookView.getStartPosition());
    }
}
